package com.education.platform.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token配置类
 *
 * @author education-platform
 * @since 2024-09-27
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    /**
     * 注册Sa-Token拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Sa-Token拦截器，校验规则为StpUtil.checkLogin()登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 放行路径配置
            SaRouter
                    // 放行根路径
                    .match("/", "/index.html")
                    // 放行静态资源
                    .match("/static/**", "/favicon.ico", "/css/**", "/js/**", "/images/**")
                    // 放行Swagger相关路径
                    .match("/swagger-ui/**", "/swagger-ui.html", "/swagger-ui/index.html")
                    .match("/v3/api-docs/**", "/v3/api-docs", "/v3/api-docs/swagger-config")
                    .match("/swagger-resources/**", "/swagger-resources")
                    .match("/webjars/**")
                    // 放行Knife4j相关路径
                    .match("/doc.html", "/doc.html/**", "/doc.html#/**")
                    .match("/knife4j/**")
                    // 放行认证相关接口
                    .match("/api/auth/login", "/api/auth/register")
                    .match("/api/auth/sms-send", "/api/auth/forgot-password")
                    // 放行测试接口
                    .match("/api/test/**")
                    // 放行需求查看接口（不需要登录）
                    .match("/api/demand/page", "/api/demand/hot", "/api/demand/{id}")
                    // 放行健康检查等系统接口
                    .match("/actuator/**", "/health/**")
                    .match("/error")
                    // 放行OPTIONS预检请求
//                    .match(req -> "OPTIONS".equals(req.getMethod()))
                    .free(r -> {
                        // 放行逻辑：不做任何处理
                    })
                    // 其他路径需要登录验证
                    .notMatch("/**")
                    .check(r -> StpUtil.checkLogin());
        })).addPathPatterns("/**")
          .excludePathPatterns(
                // 排除Swagger和Knife4j相关路径
                "/swagger-ui/**", "/v3/api-docs/**", "/doc.html", "/knife4j/**", "/webjars/**",
                // 排除静态资源
                "/static/**", "/favicon.ico", "/css/**", "/js/**", "/images/**",
                // 排除认证接口和测试接口
                "/api/auth/login", "/api/auth/register", "/api/auth/sms-send", "/api/auth/forgot-password",
                "/api/test/**",
                // 排除需求查看接口
                "/api/demand/page", "/api/demand/hot", "/api/demand/*"
          );
    }
}
